package cn.com.bsoft.cloud.controller

import java.util.Arrays.asList
import java.util.concurrent.Callable
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executors
import java.util.concurrent.FutureTask

/**
 * Created on 2016/5/18.
 */
class CallableImpl(private val acceptStr: String) : Callable<String> {

    @Throws(Exception::class)
    override fun call(): String {
        // 任务阻塞 1 秒
        Thread.sleep(1000)
        return this.acceptStr + " append some chars and return it!"
    }

    companion object {


        @Throws(ExecutionException::class, InterruptedException::class)
        @JvmStatic
        fun main(args: Array<String>) {
            val callable = CallableImpl("my callable test!")
            val task = FutureTask(callable)
            val beginTime = System.currentTimeMillis()
            // 创建线程
            Thread(task).start()
            // 调用get()阻塞主线程，反之，线程不会阻塞
            val result = task.get()
            val endTime = System.currentTimeMillis()
            println("hello : " + result)
            println("cast : " + (endTime - beginTime) / 1000 + " second!")
        }
    }
}


class RunnableImpl(private val acceptStr: String) : Runnable {

    override fun run() {
        try {
            // 线程阻塞 1 秒，此时有异常产生，只能在方法内部消化，无法上抛
            Thread.sleep(1000)
        } catch (e: InterruptedException) {
            e.printStackTrace()
        }

        // 最终处理结果无法返回
        println("hello : " + this.acceptStr)
    }

    companion object {


        @JvmStatic
        fun main(args: Array<String>) {
            val runnable = RunnableImpl("my runable test!")
            val beginTime = System.currentTimeMillis()
            Thread(runnable).start()
            val endTime = System.currentTimeMillis()
            println("cast : " + (endTime - beginTime) / 1000 + " second!")
        }
    }
}



object Sums {

    internal class Sum(private val from: Long, private val to: Long) : Callable<Long> {

        override fun call(): Long? {
            var acc: Long = 0
            for (i in from..to) {
                acc = acc + i
            }
            println(Thread.currentThread().name + " : " + acc)
            return acc
        }
    }

    @Throws(Exception::class)
    @JvmStatic
    fun main(args: Array<String>) {
        val executor = Executors.newFixedThreadPool(6)
        val results = executor.invokeAll(asList<Sum>(
                Sum(0, 10), Sum(0, 1000), Sum(0, 1000000),Sum(0, 2222),Sum(0, 33333),Sum(0, 444444),Sum(0, 555555)
        ))
        executor.shutdown()

        for (result in results) {
            println(result.get())
        }
    }
}